package com.ruoyi.web.controller.transaction;

import com.ruoyi.basedata.domain.Bank;
import com.ruoyi.basedata.domain.ConfirmResult;
import com.ruoyi.basedata.service.IBankService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SignUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.merchant.domain.MpMerchant;
import com.ruoyi.merchant.service.IMpMerchantService;
import com.ruoyi.transaction.domain.*;
import com.ruoyi.transaction.service.ITransactionWithdrawalService;
import com.ruoyi.web.controller.merchantTransaction.MerchantTransactionWithdrawalController;
import com.ruoyi.withdrawalParam.domain.WithdrawalCheckRsp;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 *  信息操作处理
 * 
 * @author ruoyi
 * @date 2019-05-07
 */
@Controller
@RequestMapping("/transaction/transactionWithdrawal")
public class TransactionWithdrawalController extends BaseController
{

    private String prefix = "transaction/transactionWithdrawal";
	Logger log = LoggerFactory.getLogger(MerchantTransactionWithdrawalController.class);

	@Autowired
	private ITransactionWithdrawalService transactionWithdrawalService;
	@Autowired
	private IMpMerchantService merchantService;
	@Autowired
	private IBankService bankService;

	// 内部-代付状态查询
	@Value("${reqUrlConfig.managerCheckWithdrawal}")
	private String managerCheckWithdrawal;
	// 外部-代付状态查询
	@Value("${reqUrlConfig.merchantCheckWithdrawal}")
	private String merchantCheckWithdrawal;
	// 内部-核销
	@Value("${reqUrlConfig.managerWithdrawal}")
	private String managerWithdrawal;
	// 审核 - 内部
	@Value("${reqUrlConfig.managerSureApply}")
	private String managerSureApply;
	
	@RequiresPermissions("transaction:transactionWithdrawal:view")
	@GetMapping()
	public String transactionWithdrawal()
	{
	    return prefix + "/transactionWithdrawal";
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("transaction:transactionWithdrawal:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(TransactionWithdrawal transactionWithdrawal)
	{
		startPage();
        List<TransactionWithdrawal> list = transactionWithdrawalService.selectTransactionWithdrawalList(transactionWithdrawal);
		return getDataTable(list);
	}





	/**
	 * 导出列表
	 */
	@RequiresPermissions("transaction:transactionWithdrawal:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TransactionWithdrawal transactionWithdrawal)
    {
    	List<TransactionWithdrawal> list = transactionWithdrawalService.selectTransactionWithdrawalList(transactionWithdrawal);
		List<TransactionWithdrawalExport> withdrawalExportList = dataConvert(list);
        ExcelUtil<TransactionWithdrawalExport> util = new ExcelUtil<TransactionWithdrawalExport>(TransactionWithdrawalExport.class);
        return util.exportExcel(withdrawalExportList, "transactionWithdrawal");
    }


	/**
	 * 数据转换
	 */
	public static List<TransactionWithdrawalExport> dataConvert(List<TransactionWithdrawal> list) {
		List<TransactionWithdrawalExport> exportList = new ArrayList<>();
		for (TransactionWithdrawal transactionWithdrawal : list) {
			TransactionWithdrawalExport withdrawalExport = new TransactionWithdrawalExport();
			BeanUtils.copyProperties(withdrawalExport, transactionWithdrawal);
			BigDecimal yuan = new BigDecimal("100");
			// 代付金额
			withdrawalExport.setFee(transactionWithdrawal.getFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 申请金额
			withdrawalExport.setSubFee(transactionWithdrawal.getSubFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 渠道出账
			withdrawalExport.setChFee(transactionWithdrawal.getChFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 商户出账
			withdrawalExport.setMchFee(transactionWithdrawal.getMchFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 财务入账
			withdrawalExport.setFinFee(transactionWithdrawal.getFinFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 渠道代付手续费
			withdrawalExport.setChannelWithdrawalFee(transactionWithdrawal.getChannelWithdrawalFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 商户代付手续费
			withdrawalExport.setChannelMchWithdrawalFee(transactionWithdrawal.getChannelMchWithdrawalFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));

			// 代付状态
			if (transactionWithdrawal.getStatus() == 1) {
				withdrawalExport.setWithdrawStatus("下单失败");
			}else if (transactionWithdrawal.getStatus() == 2) {
				withdrawalExport.setWithdrawStatus("下单超时");
			}else if (transactionWithdrawal.getStatus() == 3) {
				withdrawalExport.setWithdrawStatus("冻结中");
			}else if (transactionWithdrawal.getStatus() == 4) {
				withdrawalExport.setWithdrawStatus("未代付");
			}else if (transactionWithdrawal.getStatus() == 5) {
				withdrawalExport.setWithdrawStatus("已代付");
			}
			// 商户通知状态
			if (transactionWithdrawal.getMerchantNotifyStatus() == -1) {
				withdrawalExport.setNotifyStatus("无效");
			}else if (transactionWithdrawal.getMerchantNotifyStatus() == 0) {
				withdrawalExport.setNotifyStatus("未通知");
			}else if (transactionWithdrawal.getMerchantNotifyStatus() == 1) {
				withdrawalExport.setNotifyStatus("已通知");
			}
			// 账户类型
			if (transactionWithdrawal.getBankAccountType() == 0) {
				withdrawalExport.setAccountType("对私");
			}else if (transactionWithdrawal.getBankAccountType() == 1) {
				withdrawalExport.setAccountType("对公");
			}
			exportList.add(withdrawalExport);
		}
		return exportList;
	}





	/**
	 * 新增
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存
	 */
	@RequiresPermissions("transaction:transactionWithdrawal:add")
	@Log(title = "", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(TransactionWithdrawal transactionWithdrawal)
	{		
		return toAjax(transactionWithdrawalService.insertTransactionWithdrawal(transactionWithdrawal));
	}

	/**
	 * 修改
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap)
	{
		TransactionWithdrawal transactionWithdrawal = transactionWithdrawalService.selectTransactionWithdrawalById(id);
		mmap.put("transactionWithdrawal", transactionWithdrawal);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存
	 */
	@RequiresPermissions("transaction:transactionWithdrawal:edit")
	@Log(title = "", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(TransactionWithdrawal transactionWithdrawal)
	{		
		return toAjax(transactionWithdrawalService.updateTransactionWithdrawal(transactionWithdrawal));
	}
	
	/**
	 * 删除
	 */
	@RequiresPermissions("transaction:transactionWithdrawal:remove")
	@Log(title = "", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(transactionWithdrawalService.deleteTransactionWithdrawalByIds(ids));
	}


	/**
	 * 查询代付状态
	 * @param id
	 * @return
	 */
	@PostMapping("/payConfirm")
	@ResponseBody
	public AjaxResult payConfirm(Long id){
		TransactionWithdrawal transactionWithdrawal = transactionWithdrawalService.selectTransactionWithdrawalById(id);
		Long merchantId = transactionWithdrawal.getMerchantId();
		MpMerchant merchant = merchantService.selectMpMerchantById(merchantId);
		String key = "";
		if(StringUtils.isNotNull(merchant)) {
			key = merchant.getSecretKey();
		}
		// 平台编号
		String code = transactionWithdrawal.getCode();
		// 商户编号
		String mchCode = transactionWithdrawal.getMchCode();
		// 返回结果
		String result;
		// 根据平台编号和商户编号   判断内部请求、外部请求
		if(code == mchCode || mchCode == null || "".equals(mchCode)) {
			// 内部
			JSONObject jsonObject = new JSONObject();
			// type  0支付   1代付
			jsonObject.put("type",1);
			jsonObject.put("code",code);
			String  toJson = jsonObject.toString();
			result = HttpUtils.sendPost(managerCheckWithdrawal, toJson, false);
			if (StringUtils.isNotEmpty(result)) {
				JSONObject jsonObjectResult = JSONObject.fromObject(result);
				ConfirmResult confirmResult = (ConfirmResult) net.sf.json.JSONObject.toBean(jsonObjectResult, ConfirmResult.class);
				if (confirmResult.getStatus() == 0) {
					return AjaxResult.success(confirmResult.getMsg());
				}else {
					return AjaxResult.error(confirmResult.getMsg());
				}
			}else {
				return AjaxResult.error("请求失败!");
			}
		}else {
			// 外部
			// 外部请求数据
			String data = "mch_id=" + transactionWithdrawal.getMerchantCode() + "&out_trade_no=" + transactionWithdrawal.getMchCode();
			// 进行签名
			String sign = SignUtil.getSignReq(data, key);
			data += "&sign=" + sign;
			log.info("请求的报文：" + data);
			result = HttpUtils.sendPost(merchantCheckWithdrawal, data, false);
			if (StringUtils.isNotEmpty(result)) {
				JSONObject jsonObjectResult = JSONObject.fromObject(result);
				WithdrawalCheckRsp withdrawalCheckRsp = (WithdrawalCheckRsp) net.sf.json.JSONObject.toBean(jsonObjectResult, WithdrawalCheckRsp.class);
				if (withdrawalCheckRsp.getStatus() == 0) {
					return AjaxResult.error("代付失败");
				}else if (withdrawalCheckRsp.getStatus() == 1){
					return AjaxResult.error("未到账");
				}else if (withdrawalCheckRsp.getStatus() ==2){
					return AjaxResult.success("已到账");
				}
			}else {
				return AjaxResult.error("请求失败!");
			}
		}
		return AjaxResult.error("请求失败！");
	}



	/**
	 * 查询代付状态
	 */
	@PostMapping("/confirmWithdawal")
	@ResponseBody
	public AjaxResult confirmWithdawal(ManagerReqWithdrawalSure managerReqWithdrawalSure){
		String url = "http://192.168.6.155:9082/四方支付系统/manager/managerWithdrawalSure";
		String params = JSONObject.fromObject(managerReqWithdrawalSure).toString();
		log.info("请求的报文： " + params);
		String result = HttpUtils.sendPost(url, params, false);
		if (StringUtils.isNotEmpty(result)) {
			JSONObject jsonObjectResult = JSONObject.fromObject(result);
			EmptyOrderRspPay orderRspPay = (EmptyOrderRspPay) net.sf.json.JSONObject.toBean(jsonObjectResult, EmptyOrderRspPay.class);
			if (orderRspPay.getStatus() == 1) {
				return AjaxResult.success(orderRspPay.getMsg());
			}else {
				return AjaxResult.error(orderRspPay.getMsg());
			}
		}
		return AjaxResult.error("请求异常");
	}


	/**
	 * 核销    核销弹窗
	 */
	@GetMapping("/verification")
	public String verification(){
		return prefix + "/verification";
	}


	/**
	 * 提交核销订单
	 */
	@PostMapping("/verificationOrder")
	@ResponseBody
	public AjaxResult verificationOrder(VerificationOrderReqWithdrawal orderReqWithdrawal, Integer bankId){
		try {
			Bank bank = bankService.selectBankById(bankId);
			orderReqWithdrawal.setBank_name(bank.getName());
			orderReqWithdrawal.setBank_code(bank.getCode());
			String params = JSONObject.fromObject(orderReqWithdrawal).toString();
			log.info("请求的报文： " + params);
			String result = HttpUtils.sendPost(managerWithdrawal, params, false);
			if (StringUtils.isNotEmpty(result)) {
				JSONObject jsonObjectResult = JSONObject.fromObject(result);
				EmptyOrderRspPay orderRspPay = (EmptyOrderRspPay) net.sf.json.JSONObject.toBean(jsonObjectResult, EmptyOrderRspPay.class);
				if (orderRspPay.getStatus() == 1) {
					return AjaxResult.success(orderRspPay.getMsg());
				}else {
					return AjaxResult.error(orderRspPay.getMsg());
				}
			}
			return AjaxResult.error("请求异常");
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("系统异常");
		}
	}


	/**
	 * 审核   通过/失败
	 */
	@PostMapping("/orderAudit")
	@ResponseBody
	public AjaxResult orderAudit(ManagerReqWithdrawalApplying reqWithdrawalApplying) {
		try {
			String params = JSONObject.fromObject(reqWithdrawalApplying).toString();
			log.info("请求的报文： " + params);
			String result = HttpUtils.sendPost(managerSureApply, params, false);
			if (StringUtils.isNotEmpty(result)) {
				JSONObject jsonObjectResult = JSONObject.fromObject(result);
				ManagerRspWithdrawalApplying rspWithdrawalApplying = (ManagerRspWithdrawalApplying) JSONObject.toBean(jsonObjectResult, ManagerRspWithdrawalApplying.class);
				if (rspWithdrawalApplying.getStatus() == 1) {
					return AjaxResult.success(rspWithdrawalApplying.getMsg());
				}else {
					return AjaxResult.error(rspWithdrawalApplying.getMsg());
				}
			}
			return AjaxResult.error("请求异常");
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("系统异常");
		}
	}
}
